package com.coocaa.x.service.litecontent.providers.apps;

import com.coocaa.x.framework.app.CoocaaApplication;
import com.coocaa.x.framework.utils.Android;
import com.coocaa.x.framework.utils.AsyncTask;
import com.coocaa.x.framework.utils.Cache;
import com.coocaa.x.framework.utils.LogUtils;
import com.coocaa.x.service.litecontent.data.apps.com_coocaa_app.AppData;
import com.coocaa.x.service.litecontent.providers.apps.data.MyAppDB;
import com.coocaa.x.service.litedb.data.client.LiteDBSupport;
import com.skyworth.logsdk.appstore.LogAPIForAppStore;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class GameAppsProvider {
    private static GameAppsProvider instance = null;
    private Cache<String, AppData> gameMap = new Cache<String, AppData>();

    public static GameAppsProvider getInstance() {
        if (instance == null)
            instance = new GameAppsProvider();
        return instance;
    }

    private GameAppsProvider() {
    }

    public List<AppData> getGameList(List<AppData> list) {
//        List<AppData> list = new ArrayList<AppData>();
//        list = LocalAppManager.getInstance().getInstalledAppList();
        LogUtils.d("game", "initGameList  size:" + list.size());
        try {
//            waitGameApps = true;
            MyAppDB db = new MyAppDB();
            List<LiteDBSupport> appList = db.selectAll();
            if (appList != null && appList.size() > 0) {
                if (appList.size() != list.size()) {
                    LogUtils.d("game", "loadInstalledApps  game db !=  installedApps");
                    // 存储数据库
                    return saveGameList(list);
                } else {
                    int tag = 0;
                    for (int i = 0; i < appList.size(); i++) {
                        MyAppDB app = (MyAppDB) appList.get(i);
                        if (app.type.equals("-2")) // 忽略了还有个数一致，但是有包名不匹配的问题，以后补充
                        {
                            tag += 1;
                        }
                    }
                    LogUtils.d("game", "loadInstalledApps  tag:" + tag);
                    if (tag > 0) {
                        // 存储数据库
                        return saveGameList(list);
                    } else {
//                        waitGameApps = false;
                        return getGameListFromDB(list);
                    }
                }
            } else {
                LogUtils.d("game", "loadInstalledApps  game db is null!!");
                // 存储数据库
                return saveGameList(list);
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
//            waitGameApps = false;
            LogUtils.d("game", "loadInstalledApps  game db error error!!" + e);
            e.printStackTrace();
        }
        return gameMap.values();
    }

    private List<AppData> getGameListFromDB(List<AppData> list) {
        gameMap.clear();
        try {
            MyAppDB db = new MyAppDB();
            List<LiteDBSupport> appList = db.select(null, null, null, "type = ?", new String[]{"game"});
            if (appList != null && appList.size() > 0) {
                for (int i = 0; i < list.size(); i++) {
                    for (int j = 0; j < appList.size(); j++) {
                        MyAppDB app = (MyAppDB) appList.get(j);
                        if (list.get(i).info.pkgName.equals(app.pkg)) {
                            gameMap.add(list.get(i).info.pkgName, list.get(i));
                            break;
                        }
                    }
                }
//                if (mGameListener != null)
//                {
//                    mGameListener.onCheckDB(getGameList());
//                }
            } else {
//                if (mGameListener != null)
//                {
//                    mGameListener.onCheckDB(getGameList());
//                }
            }
            return gameMap.values();
        } catch (Exception e) {
            LogUtils.d("game", "getGameListFromDB  error!!" + e);
            e.printStackTrace();
        }
        return gameMap.values();
    }

//    public List<AppData> getGameList()
//    {
////        return gameMap.values();
//        return sortGameList(gameMap.values());
//    }

//    private List<AppData> sortGameList(List<AppData> list)
//    {
//        return LocalApps.getInstance().orderAppByNBWay(list);
//    }

    private List<AppData> saveGameList(final List<AppData> list) {
        LogUtils.d("game", "saveGameList   ");
        gameMap.clear();
        removeGameDBAll();
//        new Thread()
//        {
//
//            @Override
//            public void run()
//            {
//                // TODO Auto-generated method stub
        Cache<String, AppData> appCach = new Cache<String, AppData>();
        for (AppData info : list) {
            appCach.add(info.info.pkgName, info);
        }

        Map<String, String> map = new HashMap<String, String>();
        try {
            map = CoocaaApplication.getCoocaaWebService().getAppStoreService().getAppTypeList(appCach.keys());
            if (map != null)
                LogUtils.d("game", "checkGameList  map.size:" + map.size());
        } catch (Exception e) {
            // TODO Auto-generated catch block
            LogAPIForAppStore.reportInterfaceError("获取应用包名获取应用类型", Android.throwable2String(e));
            LogUtils.e("game", "saveGameList  error!!!");
            e.printStackTrace();
        }

        if (map != null && map.keySet() != null && map.keySet().size() > 0) {
            for (String pkg : map.keySet()) {
                String type = map.get(pkg);
                LogUtils.d("game", "saveGameList  map data   pkg:" + pkg + " type:"
                        + type);
                if (type != null && type.contains("game")) {
                    gameMap.add(pkg, appCach.get(pkg));
                }
                try {
                    MyAppDB app = new MyAppDB();
                    app.setPkg(pkg);
                    app.setType(type);
                    app.insert();
                } catch (Exception e) {
                    LogUtils.d("game", "saveGameList  save db error   pkg:" + pkg + " type:"
                            + type);
                    e.printStackTrace();
                }
            }
        }
//                waitGameApps = false;
//                if (mGameListener != null)
//                {
//                    mGameListener.onCheckDB(getGameList());
//                }

//            }
//        }.start();
        return gameMap.values();
    }

    private void removeGameDBAll() {
        try {
            MyAppDB app = new MyAppDB();
            app.deleteAll();
            LogUtils.d("game", "removelGameDBAll  sucess!!!!!!");
        } catch (Exception e) {
            LogUtils.d("game", "removelGameDBAll  error!!!!!!");
            e.printStackTrace();
        }
    }

    private void addGameDB(final String pkg) {
        LogUtils.d("game", "insertAppDB  ");
//        waitGameApps = true;
        AsyncTask.runOnThread(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                String type = "";
                try {
                    type = CoocaaApplication.getCoocaaWebService().getAppStoreService().getAppTypeByPackage(pkg);
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    LogAPIForAppStore.reportInterfaceError("根据包名获取应用类型", Android.throwable2String(e));
                    e.printStackTrace();
                    type = "-1";
                }
                LogUtils.d("game", "insertAppDB  type:" + type);
                try {
                    if (type.contains("game")) {
                        AppData info = LocalAppManager.getInstance().getAppData(pkg);
                        gameMap.add(pkg, info);
//                        if (mGameListener != null)
//                        {
//                            mGameListener.onInstallGameApp(getGameList());
//                        }
                    }

                    MyAppDB app = new MyAppDB();
                    app.setPkg(pkg);
                    app.setType(type);
                    app.insert();
//                    waitGameApps = false;
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    LogUtils.d("game", "insertAppDB  error!!!");
//                    waitGameApps = false;
                    e.printStackTrace();
                }
            }
        });
    }

    private void removeGameDB(String pkg) {
        LogUtils.d("game", "removeAppDB ");
        try {
            if (gameMap.containsKey(pkg)) {
                gameMap.remove(pkg);
//                if (mGameListener != null)
//                {
//                    mGameListener.onUninstallGameApp(getGameList());
//                }
            }

            MyAppDB app = new MyAppDB();
            app.delete("pkg", pkg);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            LogUtils.d("game", "removeAppDB  error!!!");
            e.printStackTrace();
        }
    }

//    @Override
//    public void installEvent(Intent i)
//    {
//        // TODO Auto-generated method stub
//        String pkg = i.getData().getSchemeSpecificPart();
//        LogUtils.d("game", "installEvent  pkg:"+pkg);
//        addGameDB(pkg);
//    }
//
//    @Override
//    public void uninstallEvent(Intent i)
//    {
//        // TODO Auto-generated method stub
//        String pkg = i.getData().getSchemeSpecificPart();
//        LogUtils.d("game", "uninstallEvent  pkg:"+pkg);
//        removeGameDB(pkg);
//    }


//    private IAppServicePMListener.Stub gameAppstub = new IAppServicePMListener.Stub()
//    {
//
//        @Override
//        public void onInstallStart(String apkfile, String pkgname) throws RemoteException
//        {
//            // TODO Auto-generated method stub
//            
//        }
//
//        @Override
//        public void onInstallEnd(String apkfile, String pkgname, boolean success, String extra)
//                throws RemoteException
//        {
//            // TODO Auto-generated method stub
//            LogUtils.d("game", "onInstallEnd  success:"+success);
//            if(success)
//            {
//                addGameDB(pkgname);
//            }
//        }
//
//        @Override
//        public void onUninstallStart(String pkgname) throws RemoteException
//        {
//            // TODO Auto-generated method stub
//            
//        }
//
//        @Override
//        public void onUninstallEnd(String pkgname, boolean success, String extra)
//                throws RemoteException
//        {
//            // TODO Auto-generated method stub
//            LogUtils.d("game", "onUninstallEnd  success:"+success);
//            if(success)
//            {
//                removeGameDB(pkgname);
//            }
//        }
//
//        @Override
//        public void onInstalledAppsUpdate(List<AppData> apps) throws RemoteException
//        {
//            // TODO Auto-generated method stub
//            LogUtils.d("game", "onInstalledAppsUpdate  ");
//        }
//
//        @Override
//        public void onAppHasNewUpdate(List<AppUpdateBean> apps) throws RemoteException
//        {
//            // TODO Auto-generated method stub
//            
//        }
//        
//    };

}
